﻿using System;
using LitJson;
using QuickConvert.Json;

namespace QuickConvert
{
    public class Converter
    {
        public string JsonToJson(JsonToJsonConfig config)
        {
            JsonData convertData = JsonMapper.ToObject(config.ConvertStructure);

            if (convertData.IsArray)
            {
                throw new Exception("Not allowed!");
            }

            var keys = convertData.Keys;
            JsonData resData = new JsonData();
            foreach (var key in keys)
            {
                SingleItemConvertStructure conv = JsonMapper.ToObject<SingleItemConvertStructure>(convertData[key].ToJson());
                var aftStr = JsonToJsonConfig.ConvertTo(conv, config.OriStructure);
                if (conv.SaveRawStrig)
                {
                    resData[key] = aftStr;
                }
                else
                {
                    JsonData data = JsonMapper.ToObject(aftStr);
                    resData[key] = data;
                    if (!data.IsObject && !data.IsArray)
                    {
                        resData[key] = "";
                    }
                }
            }

            return resData.ToJson();
        }
    }
}
